package com.example.elm.Public

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.HomeAndSearch.HomeMainFragment
import com.example.elm.Public.ui.theme.ElmTheme
import com.example.elm.R
import com.example.elm.databinding.AddressLayoutBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import kotlin.concurrent.thread

class AddressActivity : ComponentActivity() {
    private lateinit var binding: AddressLayoutBinding
    private lateinit var addressList: ArrayList<AddressInfo>
    private var chosenList = ArrayList<Int>()
    private val server_ip = MyApplication.serverIp
    private var maxIdA = MyApplication.maxIdA
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = AddressLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        addressList = ArrayList()
        //初始化
        ReadGoodsByXml()

        // 布局管理器
        val layoutManager = LinearLayoutManager(this)
        binding.recyclerAddress.layoutManager = layoutManager
        val adapter = AddressAdapter(addressList,chosenList)
        binding.recyclerAddress.adapter = adapter


        binding.btnAddAddress.setOnClickListener {
            val intent = Intent(this, AddAddressActivity::class.java)
            startActivity(intent)
        }

        binding.searchAddress.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                TODO("Not yet implemented")
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                //
            }

            override fun afterTextChanged(p0: Editable?) {
                TODO("Not yet implemented")
            }
        })


        // 设置按钮点击事件，保存修改后的数据并返回
        binding.btnBack.setOnClickListener {
            val returnIntent = Intent()
            setResult(Activity.RESULT_CANCELED, returnIntent) // 或返回一个默认值
            finish()
        }
    }

    //适配器
    private class AddressAdapter(var addressList: ArrayList<AddressInfo>,
                                 var chosenList:ArrayList<Int>
        ) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
    {
        private val VIEW_TYPE_HEADER = 0
        private val VIEW_TYPE_ITEM = 1

        init {
            for (i in addressList.indices) {
                chosenList.add(0) // 默认所有商品的选中状态为 false
            }
        }
        override fun getItemViewType(position: Int): Int {
            return if (position == 0) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_HEADER) {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.address_common_header, parent, false
                )
                HeaderViewHolder(view)
            } else {
                val view = LayoutInflater.from(parent.context).inflate(
                    R.layout.address_common_item, parent, false
                )
                AddressViewHolder(view).itemView.setOnClickListener {
                    val AddressData = view.findViewById<TextView>(R.id.tvAddress).text.toString()
                    val returnIntent = Intent()
                    val activity = AddressViewHolder(view).itemView.context as? Activity
                    activity?.let {
                        returnIntent.putExtra("address_data", AddressData)
                        Log.d("AddressActivity", "Returning data: $AddressData")
                        it.setResult(Activity.RESULT_OK, returnIntent)
                        it.finish()
                    }
                }
                AddressViewHolder(view)
            }
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (getItemViewType(position) == VIEW_TYPE_ITEM) {
                val addressInfo = addressList[position - 1] // 减去 header 占用的位置
                (holder as AddressViewHolder).bind(addressInfo, chosenList)
            }
            // Header 不需要额外绑定逻辑，通常用于静态布局
        }
        override fun getItemCount(): Int {
            return addressList.size + 1 // 多了一个 Header View
        }

        // Header ViewHolder
        class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

        // Address ViewHolder
        class AddressViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val name: TextView = itemView.findViewById(R.id.tvName)
            val address : TextView = itemView.findViewById(R.id.tvAddress)
            val phone : TextView = itemView.findViewById(R.id.tvPhone)
            val checkItem = itemView.findViewById<CheckBox>(R.id.checkBoxItem)

            fun bind(Info: AddressInfo,chosenList:ArrayList<Int>) {
                name.text = Info.name
                address.text = Info.address
                phone.text = Info.user_phone
                // 使用 position - 1 访问 chosenList
                val correctedPosition = adapterPosition - 1
                if (correctedPosition >= 0 && correctedPosition < chosenList.size) {
                    checkItem.isChecked = chosenList[correctedPosition] == 1
                } else {
                    checkItem.isChecked = false // 如果越界，则设置为默认值
                }
            }
        }
    }



    // 通过xml读取
    fun ReadGoodsByXml(){
        val address_all = "http://$server_ip:8080/Address/get_all_Address_xml.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(address_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                // 确保在主线程更新 UI
                if (!responseData.isNullOrEmpty()) {
                    parseXml(responseData.trim()) // 解析返回的数据
                } else {
                    Log.d("GetAddress", "没有数据")
                }
            }
            catch (e: Exception){
                e.printStackTrace()
                Log.d("GetAddress", "加载失败，请检查网络")
            }
        }
    }
    // 解析xml
    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            addressList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var address = ""
            var username = ""
            var user_phone = ""
            var chosenStr = ""
            var idStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "address" -> address = xmlPullPaser.nextText()
                            "username" -> username = xmlPullPaser.nextText()
                            "user_phone" -> user_phone = xmlPullPaser.nextText()
                            "chosen" -> chosenStr = xmlPullPaser.nextText()
                            "id" -> idStr = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Address" == nodeName) {
                            addressList.add(
                                AddressInfo(
                                    address,
                                    username,
                                    user_phone,
                                    chosenStr.toIntOrNull()?:0,
                                    idStr.toIntOrNull()?:0
                                )
                            )
                            chosenList.add(chosenStr.toIntOrNull() ?: 0)
                            Log.d("chosenStr.toIntOrNull() ?: 0", "${chosenStr.toIntOrNull() ?: 0}")
                            val tempId = idStr.toIntOrNull()?:0
                            if (tempId >= maxIdA) {
                                maxIdA = tempId
                                Log.d("maxIdAdd", "${idStr.toIntOrNull()?:0}")
                                MyApplication.maxIdA = maxIdA
                            }
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            binding.recyclerAddress.adapter?.notifyDataSetChanged()
            Log.d("maxIdA", "${maxIdA}")
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }





}

@Composable
fun Greeting2(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview2() {
    ElmTheme {
        Greeting2("Android")
    }
}